/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package connection;

import java.util.*;
import java.net.*;
import java.io.*;
import overlaynetwork.*;
import java.util.concurrent.*;
import protocol.Packet;

public class Connection {

    private Server server;
    private OverlayNetwork overlay;
    private Hashtable <String, Client> clients;

    public Connection(OverlayNetwork overlay){

        this.overlay = overlay;

        try{
        server = new Server(this);
        server.start();
        } catch(Exception e){
            System.out.println("Errore nel server");
        }

        clients = new Hashtable <String,  Client>();

    }

    public void connect(InetSocketAddress addressServerRemote)throws Exception{
        Client client = new Client(addressServerRemote);

        clients.put(addressServerRemote.toString(), client);
        
     
        
    }

    public void sendPacket(Packet packet){
       /* ottengo il client tramite get e l'inetAddress
        * e invio il packet se è un messaggio in broadcasting
        * lo invio a tutti
        */
        try{
          
        if(packet.getReceiver()!=null){
            ((Client)clients.get(packet.getReceiver().toString())).sendPacket(packet);

        }

        else{
           Enumeration c = clients.elements();
           while(c.hasMoreElements()){
              ((Client)c.nextElement()).sendPacket(packet);
           }

        }
        }catch(Exception e){
            System.err.println("errore in send packet");
            e.printStackTrace();
        }
            

    }


    public InetSocketAddress getInetSocketAddress(){
        return (InetSocketAddress)server.getSocketAddress();
    }

    public LinkedBlockingQueue<Packet> getQPackets(){
        return overlay.getQPackets();
    }




}
